package com.zdy.DeadLock;

/**
 * Created by 逸足天涯
 * on 3/9/2020.
 */
//死锁: 多个线程互相抱着对方的资源形成死锁。
public class DeadLock {
    public static void main(String[] args) {
        MakeUp g1 = new MakeUp(0,"灰姑娘");
        MakeUp g2 = new MakeUp(1,"灰姑娘");
        g1.start();
        g2.start();
    }
}

//
class Lipstick{}

class Mirror{

}

class MakeUp extends Thread{
    //需要的资源只有一份，用static 来保证只有一份
    static Lipstick lipstick = new Lipstick();
    static Mirror mirror = new Mirror();

    int choice;//选择
    String girlName;//使用化妆品的人
    MakeUp(int choice,String girlName){
        this.choice = choice;
        this.girlName = girlName;
    }
    @Override
    public void run() {
        makeup();
    }
    //化妆，互相持有对方的锁。
    private void makeup(){
        if(choice == 0){
            synchronized (lipstick){
                System.out.println(this.girlName+ "获得口红锁");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
            synchronized (mirror){
                System.out.println(this.girlName+"获得镜子锁");
            }
        }else {
            synchronized (mirror){
                System.out.println(this.girlName+ "获得镜子锁");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
            synchronized (lipstick){
                System.out.println(this.girlName+"获得口红锁");
            }

        }
    }
}